#include "CImage.h"
#include "CMbmImage.h"
#include "writablebitmap.h"
#include "global.h"
#include <BITSTD.H>
#include "CGeneralImage.h"

CImage::CImage() : iRef(0),
iLoaded(EFalse)
{
}

CImage::~CImage()
{
}

CImage* CImage::CreateImage(const THcImageLocation& aLocation)
{
	CImage* retImage = NULL;
	
	if(!aLocation.iValid)
		return NULL;
	
	switch(aLocation.iType)
	{
	case THcImageLocation::ELTFileMbm:
		retImage = new(ELeave) CMbmImage;
		break;
	case THcImageLocation::ELTFileGeneral:
		retImage = new(ELeave) CGeneralImage;
		break;
	default:
		break;
	
	}

	retImage->iLocation = aLocation;
	retImage->ConstructL();
	
	return retImage;
}

void CImage::AddRef()
	{
	iRef++;
	}

void CImage::Release()
	{
	iRef--;
	if(iRef <= 0)
		delete this;
	}

THcImageLocation& CImage::GetImageLocation()
{
	return iLocation;
}

TSize CImage::GetSize()
{
	return iSize;
}

TBool CImage::IsLoaded()
{
	return iLoaded;
}

void CImage::ConstructL()
	{
	return;
	}
void CImage::Draw(CBitmapContext& /*aGc*/,const TRect& /*aRc*/)
	{
	return;
	}

void CImage::Draw(CBitmapContext& /*aGc*/,const TRect& /*aRc*/,TSize /*aCorner*/,TInt /*aOpacity*/)
	{
	}

CFbsBitmap* CImage::CreateMask(const TSize& aCorner, TInt aOpacity, const TSize& aSize, TBool aInvertMask, CFbsBitmap* aOrginal)
{
	CFbsBitmap* mask =  aOrginal;
	if(aCorner.iWidth!=0 || aCorner.iHeight!=0 || aOpacity!=255) 
	{
		CWritableBitmap* helper = UIControlEnv::Static()->HelperBitmap(1, aSize);
		helper->Gc().SetBrushStyle(CGraphicsContext::ESolidBrush);
		helper->Gc().SetPenStyle(CGraphicsContext::ENullPen);
		
		if(aCorner.iWidth!=0 || aCorner.iHeight!=0) 
		{
			helper->Gc().SetBrushColor(TRgb::Gray256(0));
			helper->Gc().Clear();
			
			helper->Gc().SetBrushColor(TRgb::Gray256(aOpacity));
			if(aCorner.iWidth==9999)
				helper->Gc().DrawEllipse(TRect(TPoint(0,0), aSize));
			else
				helper->Gc().DrawRoundRect(TRect(TPoint(0,0), aSize), aCorner);
		}
		else 
		{
			helper->Gc().SetBrushColor(TRgb::Gray256(aOpacity));
			helper->Gc().Clear();
		}

		if(mask)
		{
			helper->Gc().SetBrushStyle(CGraphicsContext::ENullBrush);
			if(mask->DisplayMode()==EGray2)
				helper->Gc().BitBltMasked(TPoint(0,0), mask, TRect(TPoint(0,0), aSize), mask, !aInvertMask);
			else 
			{
				TBitmapUtil bu1(mask),bu2(helper);
				bu1.Begin(TPoint(0,0));
				bu2.Begin(TPoint(0,0));
				for(TInt i=0;i<aSize.iHeight;i++) 
				{
					bu1.SetPos(TPoint(0, i));
					bu2.SetPos(TPoint(0, i));
					for(TInt j=0;j<aSize.iWidth;j++) 
					{
						TUint32 c = bu1.GetPixel();
						c = c * aOpacity/255;
						bu2.SetPixel(c);
						bu1.IncXPos();
						bu2.IncXPos();
					}
				}
				bu1.End();
				bu2.End();
			}
		}
		
		mask = helper;
	}
	
	return mask;
}
